package com.app.micaihu.view.main.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.viewpager.widget.ViewPager;

import com.android.volley.VolleyError;
import com.app.base.BaseFragment;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.config.Channel;
import com.app.micaihu.bean.game.GameDownloadEntity;
import com.app.micaihu.bean.infor.UserInfor;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.custom.components.downandupload.DownloadUtils;
import com.app.micaihu.db.NewsDBSqlHelper;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.IPushManager;
import com.app.micaihu.manager.ServiceDeliveryManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.utils.ImageLoadUtils;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.videoplayer.JCVideoPlayer;
import com.app.micaihu.view.main.MainActivity;
import com.app.micaihu.view.main.adapter.TabLayoutViewPageAdapter;
import com.app.micaihu.view.home.exclusive.fragment.ExclusiveListFragment;
import com.app.micaihu.view.home.focusnews.fragment.FocusNewsListFragment;
import com.app.micaihu.view.main.game.GameActivity;
import com.app.micaihu.view.main.game.GameDownloadActivity;
import com.app.micaihu.view.main.game.fragment.GameCenterFragment;
import com.app.micaihu.view.home.knowledge.fragment.KnowledgeListFragment;
import com.app.micaihu.view.home.original.fragment.OriginalVideoListFragment;
import com.app.micaihu.view.home.questions.fragment.QuestionsListFragment;
import com.app.micaihu.view.search.SearchActivity;
import com.app.micaihu.view.user.userinfo.activity.MyHomepageDynamicActivity;
import com.app.micaihu.view.user.usertask.UserTaskActivity;
import com.app.micaihu.view.utils.DownloadAgainUtils;
import com.app.okhttplib.bean.DownloadFileInfo;
import com.app.okhttplib.callback.ProgressCallback;
import com.app.utils.biz.Biz;
import com.app.utils.util.DateUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ViewUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 首页fragment
 * Created by linkai on 2016/7/14.
 */
public class HomeFragment extends BaseFragment implements MainActivity.OnRefreshingListener, View.OnClickListener, ViewPager.OnPageChangeListener {

    private Activity mActivity;
    private ImageView mFlushView;//刷新view
    private ViewPager mViewPager;
    private ImageView ivUserIcon;
    private TextView tvSearchKey;

    /************
     * 逻辑数据
     *************/
    private ArrayList<Fragment> fragments = new ArrayList<Fragment>();//新闻页面集合
    /**
     * 咨询页面刷新
     */
    private Animation rotateAnimation;//自转动画
    private FrameLayout taskBtn;
    private LinearLayout llSearch;
    private View taskDot;
    private boolean isShowGame;

    private TabLayout tabLayout;
    private FrameLayout flGame;
    private View gameDot;
    private HashMap<String, Object> map = new HashMap<>();

    @Override
    public void onAttach(Activity activity) {
        this.mActivity = activity;
        super.onAttach(activity);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_page1;
    }

    @Override
    protected void setData() {
        hideLoading();
        isShowGame = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.isGameShow, false);
        View rootView = getRootView();
        if (rootView != null) {
            rootView.findViewById(R.id.llContent).setPadding(0,
                    BarUtils.getStatusBarHeight() + SizeUtils.dp2px(2),
                    0, SizeUtils.dp2px(7));
            tvSearchKey = rootView.findViewById(R.id.tvSearchKey);
            tvSearchKey.setText("搜索您感兴趣的");
            tabLayout = rootView.findViewById(R.id.tabLayout);

            mViewPager = rootView.findViewById(R.id.mViewPager);
            ivUserIcon = rootView.findViewById(R.id.ivUserIcon);
            flGame = rootView.findViewById(R.id.flGame);
            gameDot = rootView.findViewById(R.id.gameDot);

            //icon and dot
            taskBtn = rootView.findViewById(R.id.taskBtn);
            taskDot = rootView.findViewById(R.id.taskDot);
            llSearch = rootView.findViewById(R.id.llSearch);
            taskBtn.setVisibility(View.VISIBLE);

            String channel = SPUtils.getInstance().getString(ConfigKeyConstant.channel);
            if (StringUtils.isEmpty(channel)) {
                loadChannel();
            } else {
                List<Channel> list = GsonUtils.fromJson(channel, new TypeToken<List<Channel>>() {
                }.getType());
                if (CollectionUtils.isEmpty(list)) {
                    loadChannel();
                } else {
                    initFragment(list);
                }
            }
        }
        if (isShowGame) {
            flGame.setVisibility(View.VISIBLE);
//            tvSearchKey.setText("搜索您想要的游戏");
        } else {
//            tvSearchKey.setText("搜索您感兴趣的");
            flGame.setVisibility(View.GONE);
        }

        LiveEventBus.get(Config.EventBus.loginSuccess, Boolean.class).observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean loginSuccess) {
                ViewUtils.runOnUiThreadDelayed(() -> initHeadIcon(), 500);
            }
        });
    }

    @Override
    protected void addListeners() {
        taskBtn.setOnClickListener(this);
        llSearch.setOnClickListener(this);
        ivUserIcon.setOnClickListener(this);
        mViewPager.addOnPageChangeListener(this);
        flGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                enterPager(GameDownloadActivity.class);
            }
        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                CharSequence title = tab.getText();
                if (title != null) {
                    if ("要闻".contentEquals(title)) {
                        map = UmEventId.INSTANCE.getTopnav_importantnews();
                    } else if ("推荐".contentEquals(title)) {
                        map = UmEventId.INSTANCE.getTopnav_recommend();
                    } else if ("原创".contentEquals(title)) {
                        map = UmEventId.INSTANCE.getTopnav_original();
                    } else if ("热点".contentEquals(title)) {
                        map = UmEventId.INSTANCE.getTopnav_hotspot();
                    } else if ("游戏".contentEquals(title)) {
                        map = UmEventId.INSTANCE.getTopnav_game();
                    } else if ("视频".contentEquals(title)) {
                        map = UmEventId.INSTANCE.getTopnav_video();
                    } else if ("问答".contentEquals(title)) {
                        map = UmEventId.INSTANCE.getTopnav_answer();
                    }
                    MobclickAgentUtils.event(UmEventId.nav_top, map);
                }


            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }


    @Override
    protected void lazyLoad() {

    }

    @Override
    public void onResume() {
        super.onResume();
        //刷新任务中心的小红点
        initRedDot();
        if (ServiceDeliveryManager.getSingleton().getCurrentFragment() == 0) {
            ServiceDeliveryManager.getSingleton().showActivityDialog(getActivity(), ServiceDeliveryManager.DELIVERY_POSITION_MAIN);
        }
        initHeadIcon();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            initHeadIcon();
        }
    }

    private void initHeadIcon() {
        if (isShowGame) {
            DownloadAgainUtils.showGameDot(gameDot);
        }

        UserInfor userInfor = UserInforManager.getInstance().getUserInfor();
        if (userInfor != null && !StringUtils.isEmpty(Biz.getInstance().uid())) {
            ImageLoadUtils.loadCircleImage(UserInforManager.getInstance().getUserInfor().getHeadPic(), ivUserIcon);
        } else {
            ImageLoadUtils.loadCircleImage(R.drawable.user_head_def, ivUserIcon);
        }
    }

    /**
     * 初始化Fragment新闻页面
     */
    private void initFragment(List<Channel> channelList) {
        fragments.clear();// 清空
        List<String> titles = new ArrayList<>();
        for (Channel item : channelList) {
            if (Config.ChannelType.isGame.equals(item.getType())) {
                if (isShowGame) {
                    GameCenterFragment gameFragment = new GameCenterFragment();
                    gameFragment.setOnRefreshingListener(this);
                    fragments.add(gameFragment);
                    titles.add(item.getTitle());
                    tabLayout.addTab(tabLayout.newTab());
                }
            } else if (Config.ChannelType.isVideoGame.equals(item.getType())) {
                KnowledgeListFragment knowledgeListFragment = new KnowledgeListFragment();
                knowledgeListFragment.setOnRefreshingListener(this);
                fragments.add(knowledgeListFragment);
                titles.add(item.getTitle());
                tabLayout.addTab(tabLayout.newTab());
            } else if (Config.ChannelType.isQuestion.equals(item.getType())) {
                QuestionsListFragment questionsListFragment = new QuestionsListFragment();
                questionsListFragment.setOnRefreshingListener(this);
                fragments.add(questionsListFragment);
                titles.add(item.getTitle());
                tabLayout.addTab(tabLayout.newTab());
            } else if (Config.ChannelType.isVideo.equals(item.getType())) {
                OriginalVideoListFragment videoListFragment = new OriginalVideoListFragment();
                videoListFragment.setOnRefreshingListener(this);
                fragments.add(videoListFragment);
                titles.add(item.getTitle());
                tabLayout.addTab(tabLayout.newTab());
            } else if (Config.ChannelType.isExclusives.equals(item.getType())) {
                ExclusiveListFragment exclusiveListFragment = new ExclusiveListFragment();
                Bundle bundle = new Bundle();
                bundle.putString(Config.Extra.id, item.getId());
                exclusiveListFragment.setArguments(bundle);
                exclusiveListFragment.setOnRefreshingListener(this);
                fragments.add(exclusiveListFragment);
                titles.add(item.getTitle());
                tabLayout.addTab(tabLayout.newTab());
            } else if (Config.ChannelType.isFocusNews.equals(item.getType())) {
                FocusNewsListFragment focusNewsListFragment = new FocusNewsListFragment();
                focusNewsListFragment.setOnRefreshingListener(this);
                fragments.add(focusNewsListFragment);
                titles.add(item.getTitle());
                tabLayout.addTab(tabLayout.newTab());
            } else {
                NewsFragment newFragment = new NewsFragment();
                Bundle data = new Bundle();
                data.putString(Config.Extra.id, item.getId());
                data.putString(Config.Extra.name, item.getTitle());
                data.putString("type", TypeConstant.CHANNEL_TYPE_NEWS);
                newFragment.setArguments(data);
                newFragment.setOnRefreshingListener(this);
                fragments.add(newFragment);
                titles.add(item.getTitle());
                tabLayout.addTab(tabLayout.newTab());
            }
        }
        TabLayoutViewPageAdapter viewPage2Adapter = new TabLayoutViewPageAdapter(getChildFragmentManager(), fragments, titles);
        mViewPager.setAdapter(viewPage2Adapter);
        tabLayout.setupWithViewPager(mViewPager);
        if (channelList.size() > 1) {
            mViewPager.setCurrentItem(1);
        }
        mViewPager.setOffscreenPageLimit(titles.size());

    }

    private void loadChannel() {
        //更新栏目
        HttpListener<DataBean<List<Channel>>> httpListener = new HttpListener<DataBean<List<Channel>>>() {
            @Override
            public void onError(VolleyError error) {
                List<Channel> channelList = new ArrayList<>();
                Channel channel = new Channel();
                channel.setId("1");
                channel.setTitle("推荐");
                channel.setType(Config.ChannelType.isNews);
                channelList.add(channel);
                initFragment(channelList);
            }

            @Override
            public void onSuccess(DataBean<List<Channel>> response) {
                LogUtils.e("Channel", response);
                if (response.noError()) {
                    initFragment(response.getData());
                }

            }
        };
        HttpUtils.addPostRequest(URIContant.channel, new TypeToken<DataBean<List<Channel>>>() {
        }.getType(), getClassTag(), null, httpListener);
    }

    /**
     * 返回当前选中的页面下标
     *
     * @return
     */
    public int getCurrent() {
        if (mViewPager == null) {
            return 0;
        }
        return mViewPager.getCurrentItem();
    }

    /* 刷新当前页面数据 */
    public void flushCurrentPage(ImageView view) {
        if (fragments == null || mViewPager == null) {
            return;
        }
        mFlushView = view;
        mFlushView.setImageResource(R.drawable.tabbar_break_sel);
        if (rotateAnimation == null) {
            rotateAnimation = AnimationUtils.loadAnimation(AppApplication.getInstance(), R.anim.rotate_360);
            LinearInterpolator lin = new LinearInterpolator();
            rotateAnimation.setInterpolator(lin);
            rotateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    if (mFlushView != null) {
                        mFlushView.setImageResource(R.drawable.tabbar_infor_sel);
                    }
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        }
        mFlushView.startAnimation(rotateAnimation);
        if (fragments.get(mViewPager.getCurrentItem()) instanceof NewsFragment) {
            NewsFragment currentFragment = (NewsFragment) fragments.get(mViewPager.getCurrentItem());
            if (currentFragment != null) {
                currentFragment.flushData();
            }
        } else if (fragments.get(mViewPager.getCurrentItem()) instanceof GameCenterFragment) {
            GameCenterFragment currentFragment = (GameCenterFragment) fragments.get(mViewPager.getCurrentItem());
            if (currentFragment != null) {
                currentFragment.flushData();
            }
        } else if (fragments.get(mViewPager.getCurrentItem()) instanceof OriginalVideoListFragment) {
            OriginalVideoListFragment currentFragment = (OriginalVideoListFragment) fragments.get(mViewPager.getCurrentItem());
            if (currentFragment != null) {
                currentFragment.flushData();
            }
        } else if (fragments.get(mViewPager.getCurrentItem()) instanceof ExclusiveListFragment) {
            ExclusiveListFragment currentFragment = (ExclusiveListFragment) fragments.get(mViewPager.getCurrentItem());
            if (currentFragment != null) {
                currentFragment.flushData();
            }
        } else if (fragments.get(mViewPager.getCurrentItem()) instanceof FocusNewsListFragment) {
            FocusNewsListFragment currentFragment = (FocusNewsListFragment) fragments.get(mViewPager.getCurrentItem());
            if (currentFragment != null) {
                currentFragment.flushData();
            }
        } else if (fragments.get(mViewPager.getCurrentItem()) instanceof KnowledgeListFragment) {
            KnowledgeListFragment currentFragment = (KnowledgeListFragment) fragments.get(mViewPager.getCurrentItem());
            if (currentFragment != null) {
                currentFragment.flushData();
            }
        } else if (fragments.get(mViewPager.getCurrentItem()) instanceof QuestionsListFragment) {
            QuestionsListFragment currentFragment = (QuestionsListFragment) fragments.get(mViewPager.getCurrentItem());
            if (currentFragment != null) {
                currentFragment.flushData();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        //选中第一个栏目时 显示dialog
        if (!hidden && AppConfigTools.isShowPushDialog) {
            IPushManager.getInstance().showFoucsDialog(getActivity(), null, "");
        }
    }


    @Override
    public void onDataRefreshingStart() {

    }

    @Override
    public void onDataRefreshingEnd() {
        if (mFlushView != null) {
            //清除动画
            mFlushView.clearAnimation();
        }
    }

    public void resetFlushViewBg() {
        if (mFlushView != null) {
            ViewUtils.runOnUiThreadDelayed(new Runnable() {
                @Override
                public void run() {
                    mFlushView.setImageResource(R.drawable.tabbar_infor_nor);

                }
            }, 100);
        }

    }

    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            //任务中心
            case R.id.taskBtn:
                startActivity(new Intent(getContext(), UserTaskActivity.class));
                StatService.onEvent(getContext(), "063", "左上角作战中心", 1);//统计事件的点击次数
                break;
            //游戏
            case R.id.gameBtn:
                startActivity(new Intent(getContext(), GameDownloadActivity.class));
                StatService.onEvent(getContext(), "063", "左上角我的游戏", 1);//统计事件的点击次数
                break;
            //搜索
            case R.id.llSearch:
                MobclickAgentUtils.event(UmEventId.searchbox_click, "首页搜索框点击");
                Intent intent = new Intent(getContext(), SearchActivity.class);
                startActivity(intent);
                StatService.onEvent(getContext(), "063", "右上角搜索", 1);//统计事件的点击次数
                break;
            case R.id.ivUserIcon:
                if (UserInforManager.getInstance().isLogin()) {
                    Intent intent2 = new Intent(mActivity, MyHomepageDynamicActivity.class);
                    intent2.putExtra(Config.Extra.PARAMETER1, UserInforManager.getInstance().getUserInfor().getUid());
                    startActivity(intent2);
                } else {
                    UserInforManager.getInstance().toLoginPage(mActivity);
                }
                break;
        }
    }

    /**
     * 刷新任务任务中心红点---如果今日没有进入过任务中心,就显示
     */
    private void initRedDot() {
        if (taskDot == null) return;
        if (!UserInforManager.getInstance().isLogin()) {//没登录，显示红点
            taskDot.setVisibility(View.VISIBLE);
        } else {
            //本地记录的时间
            String localMillis = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.signDay + UserInforManager.getInstance().getUserInfor().getUid(), "");
            //当前时间
            String currentDayStr = DateUtils.getCurrentTime("yyyy/MM/dd");
            if (currentDayStr.equals(localMillis)) {//每天是否签到
                taskDot.setVisibility(View.GONE);
            } else {
                taskDot.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //释放播放器资源
        JCVideoPlayer.releaseAllVideos();
        uploadStatic("滑动");
    }


    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void uploadStatic(String opration) {
        if (mViewPager == null) {
            return;
        }
        if (isShowGame) {
            if (mViewPager.getCurrentItem() == 0) {
                StatService.onEvent(AppApplication.getInstance(), "060", opration + "到游戏页面", 1);
            } else if (mViewPager.getCurrentItem() == 1) {
                StatService.onEvent(AppApplication.getInstance(), "060", opration + "到推荐页面", 1);
            } else {
                StatService.onEvent(AppApplication.getInstance(), "060", opration + "到视频页面", 1);
            }
        } else {
            if (mViewPager.getCurrentItem() == 0) {
                StatService.onEvent(AppApplication.getInstance(), "060", opration + "到推荐页面", 1);
            } else {
                StatService.onEvent(AppApplication.getInstance(), "060", opration + "到视频页面", 1);
            }
        }
    }


}
